import asyncio
from contextlib import asynccontextmanager

from fastapi import FastAPI
from uvicorn import Config, Server

from app.api.main import api_router
from core.config import settings
from core.db.deps import database


@asynccontextmanager
async def lifespan(app: FastAPI):
    await database.connect()
    try:
        yield
    finally:
        await database.disconnect()


app = FastAPI(title=settings.PROJECT_NAME, lifespan=lifespan)
app.include_router(api_router, prefix=settings.API_V1_STR)

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    server = Server(Config(app=app, host="0.0.0.0", port=settings.PROJECT_PORT, reload=True))
    loop.run_until_complete(server.serve())
